<template>
  <div style="padding: 5px;">
    <!-- 搜索区域 -->
    <div style="margin: 10px 0;">
      <el-input v-model="params.title" placeholder="请输入书籍名称" style="width: 20%;" @keyup.enter="load"></el-input>
      <el-button style="margin-left: 5px" type="warning" @click="reset"><i class="el-icon-refresh"></i>重置</el-button>
    </div>
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="bookId" label="书籍序号" style="width: 100px;" />
      <el-table-column prop="title" label="图书名称" />
      <el-table-column prop="author" label="作者" />
      <el-table-column prop="publisher" label="出版社" />
      <el-table-column prop="publishDate" label="出版日期" >
        <template #default="scope">
          {{ formatDate(scope.row.publishDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="category" label="分类" />
      <el-table-column prop="totalCopies" label="数量" />
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button @click="showEditDialog(scope.row)">编辑</el-button>
          <el-button @click="handleBorrow(scope.row)">借书</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div style="margin: 5px 0;">
      <el-pagination
          v-model:current-page="params.pageNum"
          v-model:page-size="params.pageSize"
          :disabled="disabled"
          :background="background"
          layout="prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
    <!-- 编辑书籍对话框 -->
    <el-dialog title="编辑书籍"  v-model="dialogFormVisible">
      <el-form :model="editBook" ref="editBookForm" label-width="120px">
        <el-form-item label="书籍名称" prop="title">
          <el-input v-model="editBook.title"></el-input>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="editBook.author"></el-input>
        </el-form-item>
        <el-form-item label="出版社" prop="publisher">
          <el-input v-model="editBook.publisher"></el-input>
        </el-form-item>
        <el-form-item label="出版日期" prop="publishDate">
          <el-date-picker v-model="editBook.publishDate" type="date" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-input v-model="editBook.category"></el-input>
        </el-form-item>
        <el-form-item label="数量" prop="totalCopies">
          <el-input v-model="editBook.totalCopies" type="number"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitEditForm('editBookForm')">提交</el-button>
          <el-button @click="editDialogVisible()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>

import request from "../../utils/request";
import { reactive, ref } from 'vue';
import moment from "moment/moment";


export default {
  name: 'BookView',
  data() {
    return {
      total: 0,
      tableData: [],
      params: {
        title: '',
        pageSize: 10,
        pageNum: 1
      },
      dialogFormVisible: ref(false),
      editBook: {
        bookId: '',
        title: '',
        author: '',
        publisher: '',
        publishDate: '',
        category: '',
        totalCopies: 0
      }
    };
  },
  created() {
    this.load();
  },
  methods: {
    load() {
      request.get('/book/page', {
        params: this.params
      }).then(res => {
        if (res.code === '200') {
          this.tableData = res.data.list;
          this.total = res.data.total;
        }
      });
    },
    showEditDialog(row) {
      this.editBook = { ...row };
      //this.editDialogVisible = true;
      this.dialogFormVisible = ref(true)
    },
    editDialogVisible(){
      this.dialogFormVisible = ref(false)
    },
    submitEditForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          request.put(`/book/update/${this.editBook.bookId}`, this.editBook)
              .then(res => {
                if (res.code === '200') {
                  this.$message.success('书籍更新成功');
                  this.dialogFormVisible = ref(false)
                  this.load(); // 重新加载表格数据
                } else {
                  this.$message.error('书籍更新失败');
                }
              })
              .catch(error => {
                console.error('Error updating book:', error);
                this.$message.error('书籍更新失败');
              });
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },
    handleBorrow(row) {
      const bookId = row.bookId;
      const loginId = localStorage.getItem('loginId');
      const username = localStorage.getItem('username');
      const borrowDate = new Date().toISOString().slice(0, 19).replace('T', ' ');

      const borrowData = {
        loginId,
        bookId,
        username,
        borrowDate,
        status: 0, // 0 表示未归还
        title: row.title,
        author: row.author,
        publisher: row.publisher,
        publishDate: row.publishDate,
        category: row.category
      };
      request.put(`/book/${bookId}`)
          .then(res => {
            if (res.code === '200') {
              request.post('/borrow/addBorrow', borrowData).then(
                  res2 => {
                    if (res2.code === '200') {
                      this.$message.success('借书成功');
                      this.load(); // 重新加载表格数据
                    }
                  })
            } else {
              this.$message.error('借书失败');
            }
          })
          .catch(error => {
            console.error('Error borrowing book:', error);
            this.$message.error('借书失败');
          });
    },
    handleSizeChange(size) {
      this.params.pageSize = size;
      this.load();
    },
    handleCurrentChange(pageNum) {
      console.log(pageNum); // test 打印
      this.params.pageNum = pageNum;
      this.load();
    },
    reset() {
      this.params = {
        title: '',
        pageSize: 10,
        pageNum: 1
      };
      this.load();
    },
    formatDate(date) {
      return moment(date).format('YYYY-MM');
    }
  }
};
</script>